package cn.iocoder.yudao.module.project.controller.admin.tcp;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.project.controller.admin.tcp.vo.SendVO;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.bind.DatatypeConverter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * @ClassName : TcpServerController
 * @Description :
 * @Author : df
 * @Date: 2021-01-07 17:15
 */
@RestController
@RequestMapping("/tcp")
public class TcpController {
    /**
     * 建立tcp连接
     * @param sendVO
     * @return
     * @throws IOException
     */
    @RequestMapping("/send")
    public CommonResult<String> send(@RequestBody SendVO sendVO) throws IOException {
        String ip = sendVO.getIp();
        Integer port = sendVO.getPort();
        // String msg = sendVO.getMsg();
        Socket socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress(ip ,port); //获取sockaddress对象
        socket.connect(socketAddress, 2000);
        System.out.println("连接服务器成功：" + socket);

        String msg = "RN";
        String result = "";
        // byte[] bytes = msg.getBytes();
        // String printHexBinary = DatatypeConverter.printHexBinary(bytes);
        // String hexStr = printHexBinary + "0D0A";
        // StringBuilder output = new StringBuilder("");
        // for (int i = 0; i < hexStr.length(); i += 2) {
        //     String tmpstr = hexStr.substring(i, i + 2);
        //     output.append((char) Integer.parseInt(tmpstr, 16));
        // }


        try {
            // 发送消息
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            out.println(msg);

            // 接收消息
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            result = in.readLine();
            System.out.println("收到服务器的消息：" + result);
            return success(result);
        } catch (IOException e) {

        } finally {
            // 关闭连接
            socket.close();
        }

        return success(result);
    }
}
